package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.SimpleDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DefaultAsyncHttpClient;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.Message;
import com.isunland.managesystem.entity.MessageDetailOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.File;
import java.text.DecimalFormat;
import java.util.HashMap;
import org.apache.http.Header;
import org.json.JSONException;

/**
 * 消息详情
 *
 * @author wangyanan
 */
@SuppressWarnings("deprecation") public class MessageDetailFragment extends BaseFragment {

  public static final String EXTRA_MESSAGE = "com.isunland.managesystem.ui.extra_message";
  public static final String EXTRA_TYPE = "com.isunland.managesystem.ui.EXTRA_TYPE";
  public static final int VALUE_SEND = 0;
  public static final int VALUE_RECEIVE = 1;

  protected static final int REQUEST_SHOW = 0;
  protected static final int REQUEST_DOWNLOAD = 1;
  protected static final String TAG = MessageDetailFragment.class.getSimpleName();
  private static final int notificationID = 2;
  private Message mMessage;
  private EditText mEtReplyContent;
  private BaseVolleyActivity mActivity;
  private Boolean mHasReply = false;
  private String mReplyContent;
  private int mType;
  private File mFile;
  private NotificationManager mNotificationManager;
  private Notification mNotification;
  private String mFilePathString;
  private String mFileName;

  public static Fragment newInstance(Message msg, int type) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_MESSAGE, msg);
    args.putInt(EXTRA_TYPE, type);
    MessageDetailFragment fragment = new MessageDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_message_detail, container, false);
    TextView mTvSendPeople = (TextView) v.findViewById(R.id.tv_sendPeople_messageDetail);
    TextView mTvSendTime = (TextView) v.findViewById(R.id.tv_sendTime_messageDetail);
    TextView mTvExtraFile = (TextView) v.findViewById(R.id.tv_extraFileName_messageDetail);
    mFilePathString = mMessage.getAndroidPath();
    LogUtil.i(TAG, "filePath=" + mFilePathString);
    if (TextUtils.isEmpty(mFilePathString)) {
      mFileName = mMessage.getFileName();

      mTvExtraFile.setText(mFileName);
    } else {
      mFileName = FileUtil.getFileNameByFilePath(mFilePathString);
      mTvExtraFile.setText(mFileName);
    }
    mTvExtraFile.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View v) {
        // 服务器android路径上寻找.
        if (!TextUtils.isEmpty(mFilePathString)) {
          mFile = new File(mFilePathString);
          if (mFile.exists()) {
            showDialog(REQUEST_SHOW);
            return;
          }
        }

        // 本地下载文件夹中寻找.
        if (!TextUtils.isEmpty(mMessage.getFileName())) {
          mFile = new File(FileUtil.getFileDir(), mMessage.getFileName());
          if (!mFile.getParentFile().exists()) {

            //noinspection ResultOfMethodCallIgnored
            mFile.getParentFile().mkdirs();
          }
          if (!mFile.exists()) {

            showDialog(REQUEST_DOWNLOAD);
          } else {
            showDialog(REQUEST_SHOW);
          }
        }
      }
    });
    TextView mTvReceivePeople = (TextView) v.findViewById(R.id.tv_receivePeople_messageDetail);
    EditText mTvContent = (EditText) v.findViewById(R.id.tv_content_messageDetail);
    mTvContent.setEnabled(false);
    mEtReplyContent = (EditText) v.findViewById(R.id.et_contentReply_messageDetail);
    TextView mTvReplyContent = (TextView) v.findViewById(R.id.tv_contentReply_messageDetail);
    if (mType == VALUE_SEND) {
      mEtReplyContent.setVisibility(View.GONE);
      mTvReplyContent.setVisibility(View.GONE);
    }
    mTvSendPeople.setText(getString(R.string.sendPeople, mMessage.getUserName()));
    mTvSendTime.setText(getString(R.string.sendtime, mMessage.getSendTime()));
    mTvReceivePeople.setText(getString(R.string.receivepeople, mMessage.getReceiverName()));
    mTvContent.setText(mMessage.getContent());
    if (mType == VALUE_RECEIVE) {

      if ("F".equalsIgnoreCase(mMessage.getIfRead())) {
        volleyPostIsRead();// 消息更改为已读.
      }
      volleyPostDetail();// 消息详情
    }
    return v;
  }

  /**
   * 下载文件
   */
  protected void downLoadFile(File file) {

    RequestParams params2 = new RequestParams("selcurFileName", mMessage.getFileName());
    params2.put("selcurFile", mMessage.getFileBlob());
    params2.put("androidPath", file.toString());
    LogUtil.i(TAG, "parmas=" + params2.toString());
    DefaultAsyncHttpClient.post(ApiConst.URL_MESSAGE_DOWNLOAD, params2,
        new FileAsyncHttpResponseHandler(mFile) {

          @Override public void onStart() {

            Toast.makeText(getActivity(), R.string.isDownLoading, Toast.LENGTH_SHORT).show();
            initNotifycation();
          }

          @Override public void onProgress(long bytesWritten, long totalSize) {
            String fileLength = mMessage.getFileLength();

            totalSize = Long.parseLong(fileLength);
            notifyProgress(bytesWritten, totalSize);
          }

          @Override public void onSuccess(int statusCode, Header[] headers, File response) {

            Toast.makeText(getActivity(), R.string.download_success, Toast.LENGTH_SHORT).show();
            // FileUtil.openFile(MessageDetailFragment.this.mFile,
            // getActivity());
            Intent intent = FileUtil.getFileIntent(MessageDetailFragment.this.mFile);
            notifyOpenFile(intent);
          }

          @Override public void onFailure(int arg0, Header[] arg1, Throwable arg2, File arg3) {
            MyUtils.dismissDialog();
            Toast.makeText(getActivity(), R.string.download_failed, Toast.LENGTH_SHORT).show();
            LogUtil.i(TAG, "responseError=" + arg0 + arg2 + arg3);
          }
        });
  }

  private void initNotifycation() {
    // PendingIntent pi = PendingIntent.getActivity(getActivity(), 0,
    // new Intent(getActivity(), MessagePagerActivity.class), 0);
    mNotificationManager =
        (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
    mNotification = new Notification();
    mNotification.icon = R.drawable.ic_launcher;// 设置通知消息的图标
    mNotification.tickerText = mFileName;// 设置通知消息的标题
    // mNotification.contentIntent = pi;

  }

  private void notifyProgress(long bytesWritten, long totalSize) {
    int progressPercentage = (int) ((bytesWritten * 100 / totalSize));

    DecimalFormat format = new DecimalFormat("0.00");
    String progress = format.format(progressPercentage);
    RemoteViews remoteViews =
        new RemoteViews(getActivity().getPackageName(), R.layout.down_notification);
    remoteViews.setImageViewResource(R.id.IconIV, R.drawable.ic_launcher);
    remoteViews.setTextViewText(R.id.progressTv, R.string.hasdownloaded + progress + "%");

    remoteViews.setProgressBar(R.id.progressBar, 100, progressPercentage, false);
    remoteViews.setTextViewText(R.id.tv_title_remoteView, mFileName);
    mNotification.contentView = remoteViews;
    mNotificationManager.notify(notificationID, mNotification);
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mMessage = (Message) getArguments().getSerializable(EXTRA_MESSAGE);
    mType = getArguments().getInt(EXTRA_TYPE);
    mActivity = (BaseVolleyActivity) getActivity();

    if (mType == VALUE_RECEIVE) {
      setTitleCustom(R.string.receiveMessageDetail);
    } else if (mType == VALUE_SEND) {
      setTitleCustom(R.string.sendMessageDetail);
    }
  }

  /**
   * 消息更改为已读.
   */
  private void volleyPostIsRead() {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_MESSAGE_READ);
    HashMap<String, String> params = new HashMap<>();
    params.put("messageId", mMessage.getId() + "");
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage successMessage = new Gson().fromJson(arg0, SuccessMessage.class);
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(successMessage.getResult())) {
          getActivity().setResult(Activity.RESULT_OK);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  /**
   * 消息详情
   */
  private void volleyPostDetail() {

    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_MESSAGE_DETAIL);
    HashMap<String, String> params = new HashMap<>();
    params.put("messageId", mMessage.getId() + "");

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {
          MessageDetailOriginal messageDetailOriginal =
              new Gson().fromJson(arg0, MessageDetailOriginal.class);
          mMessage = messageDetailOriginal.getMessageSend();
          mHasReply = messageDetailOriginal.getHasReply();

          if (mType == VALUE_RECEIVE && mHasReply) {

            String replyContent = messageDetailOriginal.getReplyContent();
            mEtReplyContent.setText(replyContent);
            mEtReplyContent.setEnabled(false);
          }
        } catch (Exception e) {
          LogUtil.e(TAG, "json error", e);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

        Toast.makeText(getActivity(), R.string.cannotgetcontent, Toast.LENGTH_SHORT).show();
        mEtReplyContent.setEnabled(false);
        MyUtils.dismissDialog();
      }
    });
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if (mType == VALUE_RECEIVE) {

      inflater.inflate(R.menu.menu_confirm, menu);
    }
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
      case android.R.id.home:

        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }

        return true;
      case R.id.menu_item_confirm:
        // Intent i=new Intent(getActivity(), MessageReplyActivity.class);
        // i.putExtra(MessageSendFragment.EXTRA_MESSAGE, mMessage);
        // startActivity(i);
        if (mHasReply) {
          Toast.makeText(getActivity(), R.string.hasReply, Toast.LENGTH_SHORT).show();// 您已经回复过这条消息
          return true;
        }
        mReplyContent = mEtReplyContent.getText().toString().trim();
        if (TextUtils.isEmpty(mReplyContent)) {
          // 请输入消息内容
          Toast.makeText(getActivity(), R.string.emptyMessageContent, Toast.LENGTH_SHORT).show();
          return true;
        }

        volleyPostReply();
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void volleyPostReply() {

    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_MESSAGE_REPLY);
    HashMap<String, String> params = new HashMap<>();

    params.put("id", mMessage.getId() + "");

    params.put("content", mReplyContent);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        try {
          MyUtils.dismissDialog();

          SuccessMessage mSuccess = new Gson().fromJson(arg0, SuccessMessage.class);
          if (mSuccess == null || mSuccess.getResult() == null) {
            Toast.makeText(getActivity(), R.string.failureSendMessage, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = mSuccess.getResult();
          if (successType.equalsIgnoreCase("1")) {
            Toast.makeText(getActivity(), R.string.successmessage, Toast.LENGTH_SHORT).show();
            getActivity().finish();
          } else {
            Toast.makeText(getActivity(), R.string.failureSendMessage, Toast.LENGTH_SHORT).show();
          }
        } catch (JsonSyntaxException e) {
          LogUtil.e(TAG, "error=" + e, e);
          Toast.makeText(getActivity(), R.string.failureSendMessage, Toast.LENGTH_SHORT).show();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  private void notifyOpenFile(Intent intent) {

    RemoteViews remoteViews =
        new RemoteViews(getActivity().getPackageName(), R.layout.down_notification);
    remoteViews.setImageViewResource(R.id.IconIV, R.drawable.ic_launcher);
    remoteViews.setTextViewText(R.id.progressTv, mFileName);
    remoteViews.setProgressBar(R.id.progressBar, 100, 100, false);
    mNotification.contentView = remoteViews;

    if (intent != null) {
      mNotification.contentIntent = PendingIntent.getActivity(getActivity(), 0, intent, 0);
    }
    mNotification.flags = Notification.FLAG_AUTO_CANCEL;
    mNotificationManager.notify(notificationID, mNotification);
    // notificationManager.cancel(notificationID);
  }

  private void showDialog(int requestCode) {
    DialogFragment dialog = null;
    switch (requestCode) {
      case REQUEST_SHOW:
        dialog = SimpleDialogFragment.newInstance(R.string.alreadyDownload, R.string.show, 0,
            android.R.string.cancel);
        break;
      case REQUEST_DOWNLOAD:
        dialog = SimpleDialogFragment.newInstance(R.string.haveNotDownload, R.string.download, 0,
            android.R.string.cancel);
        break;

      default:
        break;
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();

    if (dialog != null) {
      dialog.setTargetFragment(MessageDetailFragment.this, requestCode);
      dialog.show(fm, "");
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    switch (requestCode) {

      case REQUEST_SHOW:
        if (data != null) {

          int code = data.getIntExtra(SimpleDialogFragment.EXTRA_CHOICE,
              SimpleDialogFragment.VALUE_POSITIVE);
          if (code == SimpleDialogFragment.VALUE_POSITIVE) {// 查看

            FileUtil.openFile(mFile, getActivity());

            return;
          }
        }

        break;
      case REQUEST_DOWNLOAD:
        if (data != null) {

          int code = data.getIntExtra(SimpleDialogFragment.EXTRA_CHOICE,
              SimpleDialogFragment.VALUE_POSITIVE);
          if (code == SimpleDialogFragment.VALUE_POSITIVE) {// 下载

            downLoadFile(mFile);
            return;
          }
        }

        break;

      default:
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}
